package cn.schoolwow.quickdao.module.database.ddl.action.flow.table.common;

import cn.schoolwow.quickdao.domain.QuickDAOConfig;
import cn.schoolwow.quickdao.domain.entity.Entity;
import cn.schoolwow.quickdao.domain.entity.Property;
import cn.schoolwow.quickdao.domain.provider.DatabaseProvider;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;

public class BuildForeignKeyFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        StringBuilder sqlBuilder = (StringBuilder) flowContext.checkData("sqlBuilder");
        Entity entity = (Entity) flowContext.checkData("entity");
        QuickDAOConfig quickDAOConfig = flowContext.checkInstanceData(QuickDAOConfig.class);
        
        DatabaseProvider databaseProvider = quickDAOConfig.databaseContext.databaseProvider;

        if (quickDAOConfig.databaseOption.openForeignKey && null != entity.foreignKeyProperties && entity.foreignKeyProperties.size() > 0) {
            for (Property property : entity.foreignKeyProperties) {
                sqlBuilder.append("foreign key(" + databaseProvider.escape(property.column) + ") references ");
                String sourceTableName = quickDAOConfig.getEntityByClassName(property.foreignKey.table().getName()).tableName;
                String sourceTableColumnName = property.foreignKey.field();
                sqlBuilder.append(databaseProvider.escape(sourceTableName) + "(" + databaseProvider.escape(sourceTableColumnName) + ")" +
                        " ON UPDATE " + property.foreignKey.updateForeignKeyOption().getOperation() +
                        " ON DELETE " + property.foreignKey.deleteForeignKeyOption().getOperation());
                sqlBuilder.append(",");
            }
        }
        sqlBuilder.deleteCharAt(sqlBuilder.length() - 1);
    }

    @Override
    public String name() {
        return "构建外键关联语句";
    }
}
